package com.heima.comtroller;

import com.heima.exception.CustomException;
import com.heima.pojo.Result;
import com.heima.pojo.User;
import com.heima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    /**
     *@PathVariable ：关联请求参数 和形参
     *              无论参数名字是否相同，都会映射
     */
    /*@RequestMapping("/findById")*/
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id){
        User user = userService.findById(id);
        log.debug("findById {"+id+"}");
        if (user!=null&&!user.equals("null")){
            throw new CustomException("该用户信息不存在!");
        }
        return new Result(false,"没有查询到该用户");
    }

    @PostMapping("")
    public Result insert(@RequestBody User user){
        log.debug("insert {"+user+"}");
        int i = userService.insert(user);
        log.debug("新增了"+i+"条数据");
        return new Result(true,"创建成功",user);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id){
        int delete = userService.delete(id);
        log.debug("删除了"+delete+"条信息");
        if (delete<=0){
            throw new CustomException("该用户信息不存在!");
        }
        return new Result(true,"删除成功");
    }

    @PutMapping("")
    public Result update(@RequestBody User user){
        log.debug("update"+"{"+user+"}");
        int update = userService.update(user);
        log.debug("修改了"+update+"条数据");
        return new Result(true,"修改数据成功",user);
    }

    @GetMapping("")
    public Result findAll(){
        List<User> list = userService.findAll();
        log.debug(Arrays.toString(list.toArray()));
        return new Result(true,"查询所有信息成功",Arrays.toString(list.toArray()));
    }

}
